package com.example.test.controller;

import com.example.test.annotation.TestAopAnnotation;
import com.example.test.vo.ResultVO;
import com.example.test.entity.User;
import com.example.test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping(value = "/getUser",consumes = MediaType.APPLICATION_JSON_VALUE)
    //@TestAopAnnotation(timeout = 2000,fallBack = "fallBack")
    public ResultVO<List<User>> getUser() throws Exception {
        //Thread.sleep(3000);
        User user = new User();
        user.setId(1l);
        user.setAccount("23333");
        user.setPassword("123");
        User user2 = new User();
        user2.setId(1l);
        user2.setAccount("23333");
        user2.setPassword("123");
        List<User> al = new ArrayList<>();
        al.add(user);
        al.add(user2);
        System.out.println("----------finish----------");
        return new ResultVO<>(al);
    }

    /**
     * Validator+BindingResult
     *
     * @param user
     * @return
     */
    @PostMapping("/addUser1")
    //@TestAopAnnotation(timeout = 2000,fallBack = "fallBack")
    public String addUser(@RequestBody @Valid User user) {
        return userService.addUser(user);
    }

    @PostMapping("/addUser2")
    public String addUser2(@RequestBody @Valid User user) {
        return userService.addUser(user);
    }

    @PostMapping("/addUser3")
    public String addUser3(@RequestBody @Valid User user)throws Exception {
        throw new Exception("dd");
    }

    @PostMapping("/addUser4")
    @TestAopAnnotation(timeout = 2000,fallBack = "fallBack")
    public String addUser(@RequestBody @Valid User user, BindingResult br) throws Exception {
        //Thread.sleep(3000);
        if(br.hasErrors()){
            //throw new MyException(br.getFieldError().getCode(),br.getFieldError().getDefaultMessage());
        }
        return userService.addUser(user);
    }

    public String fallBack() {
        System.out.println("请求降级，失败返回");
        return "降级";
    }

    @GetMapping("/test")
    public String testRedis() {
        /*RBucket bucket = redissonClient.getBucket("name");

        if (bucket.get() == null){
            bucket.set("com.test");
        }
        return bucket.get().toString();*/
        int n = 15 / 0;
        return "success";
    }

}
